package com.example.gzq.mymusictest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.gzq.mymusictest.Util.ActivityCollector;
import com.example.gzq.mymusictest.Util.MyApplication;
import com.example.gzq.mymusictest.domain.Person;

import org.litepal.LitePal;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by gzq on 17-7-13.
 */

public class PlayActivity extends BaseStyle {

    private static final String TAG = "PlayActivity";
    private MediaPlayer mPlayer;
    private boolean isPause = true,nav_menu=false;
    private TextView hint,username,mail;
    private String[] items=new String[]{"本地音乐","最近播放","我的下载","我的收藏","我喜欢的音乐"};
    private int[] imageIds=new int[]{R.drawable.my_music,R.drawable.recently,
            R.drawable.my_download,R.drawable.my_collection,R.drawable.my_heart
    };
    private DrawerLayout mDrawerLayout;
    private Button header_btn;
    private boolean mIsExit;
    ImageButton startPlay,play_prev,play_next,play_menu;
    View headerView;
    NavigationView navView;
    //RelativeLayout relat_header;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.play_activity);
        localBroadcastManager=LocalBroadcastManager.getInstance(this);
        LitePal.getDatabase();
        ListView list=(ListView) findViewById(R.id.play_content);
        startPlay=(ImageButton)findViewById(R.id.play_start);
        play_prev=(ImageButton)findViewById(R.id.play_prev);
        play_next=(ImageButton)findViewById(R.id.play_next);
        play_menu=(ImageButton)findViewById(R.id.play_menu);
        hint = (TextView)findViewById(R.id.hint);//获取用于显示提示信息的文本框
        startPlay.setImageResource(R.drawable.pause);
        mPlayer = MediaPlayer.create(this, R.raw.test);//重新设置要播放的音频
        setDrawerLayout();
        play_menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDrawerLayout.openDrawer(Gravity.START);
                RelativeLayout relat_header=(RelativeLayout) findViewById(R.id.logined);
                Log.d(TAG, "onClick: ---------"+mNub);
                if (!mNub.isEmpty()){
                    relat_header.setVisibility(View.VISIBLE);
                    header_btn.setVisibility(View.INVISIBLE);
                    username=(TextView)findViewById(R.id.username);
                    mail=(TextView)findViewById(R.id.mail);
                    mSetHeader();
                }else {
                    header_btn.setVisibility(View.VISIBLE);
                    relat_header.setVisibility(View.INVISIBLE);
                }
            }
        });
        startPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: --------play()");
                if (!isPause){
                    mPlayer.pause();//暂停播放
                    isPause=true; hint.setText("暂停播放。。。");
                    startPlay.setImageResource(R.drawable.pause);
                }else {
                    mPlayer.start();//继续播放
                    isPause=false;hint.setText("正在播放。。。");
                    startPlay.setImageResource(R.drawable.play);
                }
            }
        });
        play_prev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hint.setText("播放上一首。。。");
                if (isPause){
                    isPause=false;hint.setText("正在播放。。。");
                    mPlayer.start();
                    startPlay.setImageResource(R.drawable.play);
                }
            }
        });
        play_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hint.setText("播放下一首。。。");
                if (isPause){
                    isPause=false;hint.setText("正在播放。。。");
                    mPlayer.start();
                    startPlay.setImageResource(R.drawable.play);
                }
            }
        });
        list.setAdapter(mAdapter());
    }
    //接受上一个活动返回的数据
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:if (resultCode==RESULT_OK){
                mNub=data.getStringExtra("mNum");
                Log.d(TAG, "onActivityResult: mNum="+mNub);
            }
            default:
        }
    }
    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onStart: ");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop: ");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //头部菜单点击事件（弹出侧滑菜单）
        header_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(PlayActivity.this,LoginActivity.class);
                startActivityForResult(intent,1);
                mDrawerLayout.closeDrawers();
            }
        });
        Log.d(TAG, "onResume:");
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    private SimpleAdapter mAdapter(){
        List<Map<String,Object>> listItems=new ArrayList<Map<String, Object>>();
        for (int i=0;i<items.length;i++){
            Map<String,Object> listItem=new HashMap<String, Object>();
            listItem.put("header",imageIds[i]);
            listItem.put("item",items[i]);
            listItems.add(listItem);
        }
        SimpleAdapter adapter=new SimpleAdapter(this,listItems,R.layout.simple_item,
                new String[]{"item","header"},new int[]{R.id.item,R.id.header});
        return adapter;
    }
    private void setDrawerLayout(){
        final ActivityCollector activityCollector =null;
        mDrawerLayout=(DrawerLayout) findViewById(R.id.drawer_layout);
        navView = (NavigationView) findViewById(R.id.nav_view);
        navView.setItemIconTintList(null);
        headerView = navView.inflateHeaderView(R.layout.nav_header);
        header_btn=headerView.findViewById(R.id.header_btn);
        navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                item.setCheckable(true);
                switch (item.getItemId()) {
                    case R.id.nav_friends:
                        Log.d(TAG, "onOptionsItemSelected:click nav_friends!");
                        break;
                    case R.id.nav_skin:
                        //皮肤设置
                        Log.d(TAG, "onOptionsItemSelected:click nav_skin!");
                        break;
                    case R.id.nav_timing:
                        //定时播放
                        Log.d(TAG, "onOptionsItemSelected:click nav_timing!");
                        break;
                    case R.id.nav_install:
                        //系统设置
                        Log.d(TAG, "onOptionsItemSelected:click nav_install!");
                        break;
                    case R.id.nav_close:
                        //退出程序
                        activityCollector.exitApp(PlayActivity.this);
                        Log.d(TAG, "onOptionsItemSelected:click nav_close!");
                        break;
                    default:break;
                }
                mDrawerLayout.closeDrawers();
                return true;
            }
        });
    }
    private void play(){
        try {
            //mPlayer.reset();
            mPlayer = MediaPlayer.create(this, R.raw.test);//重新设置要播放的音频
            //mPlayer.prepare();//预加载音频
            mPlayer.start();//开始播放
            hint.setText("test正在播放音频.....");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void mSetHeader(){
        List<Person> persons=DataSupport.select("mname","memail").where("mtel=?",mNub).find(Person.class);
        String name="",email="";
        for (Person person:persons){
            name=person.getmName();
            email=person.getmEmail();
        }
        username.setText(name+" 你好！");
        mail.setText(email);
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mIsExit) {
                this.finish();

            } else {
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
                mIsExit = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mIsExit = false;
                    }
                }, 2000);
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onDestroy() {
        Log.d(TAG, "-------------onDestroy: ");
        super.onDestroy();
    }
}

